package com.wrl.mmall.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alipay.api.AlipayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wrl.mmall.common.Const;
import com.wrl.mmall.common.ServerResponse;
import com.wrl.mmall.common.enums.OrderStatusEnum;
import com.wrl.mmall.common.enums.PayPlatformEnum;
import com.wrl.mmall.common.enums.PaymentTypeEnum;
import com.wrl.mmall.common.enums.ProductStatusEnum;
import com.wrl.mmall.dao.*;
import com.wrl.mmall.pojo.*;
import com.wrl.mmall.service.IOrderService;
import com.wrl.mmall.util.BigDecimalUtil;
import com.wrl.mmall.util.DateTimeUtil;
import com.wrl.mmall.util.FTPUtil;
import com.wrl.mmall.util.PropertiesUtil;
import com.wrl.mmall.vo.OrderItemVo;
import com.wrl.mmall.vo.OrderProductVo;
import com.wrl.mmall.vo.OrderVo;
import com.wrl.mmall.vo.ShippingVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Service("iOrderService")
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private PayInfoMapper payInfoMapper;
    @Autowired
    private ShippingMapper shippingMapper;

    //支付
    @Override
    public ServerResponse pay(Long orderNo, Integer userId, String path) {

        //map用于返回订单号和url
        Map<String, String> resultMap = Maps.newHashMap();

        //根据userId和orderNo查出来，这个order到底存不存在
        Order order = orderMapper.selectByUserIdAndOrderNo(userId, orderNo);
        if (order == null) {
            return ServerResponse.createByErrorMessage("用户没有该订单");
        }
        resultMap.put("orderNo", String.valueOf(order.getOrderNo()));

        /*组装生成支付宝订单的各种参数*/

        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        // 需保证商户系统端不能重复，建议通过数据库sequence生成，
        String outTradeNo = order.getOrderNo().toString();

        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店消费”
        String subject = new StringBuilder().append("happymmall扫码支付，订单号：").append(outTradeNo).toString();

        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        String totalAmount = order.getPayment().toString();

        // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
        // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
        String undiscountableAmount = "0";

        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
        // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        String sellerId = "";

        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品3件共20.00元"
        String body = new StringBuilder().append("订单").append(outTradeNo).append("购买商品共").append(totalAmount).append("元").toString();

        // 商户操作员编号，添加此参数可以为商户操作员做销售统计
        String operatorId = "test_operator_id";

        // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
        String storeId = "test_store_id";

        // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088100200300400500");

        // 支付超时，定义为120分钟
        String timeoutExpress = "120m";

        // 商品明细列表，需填写购买商品详细信息，
        List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
        List<OrderItem> orderItemList = orderItemMapper.getByOrderNoByUserId(orderNo, userId);
        // 遍历创建多个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
        for (OrderItem oi : orderItemList) {
            GoodsDetail goods1 = GoodsDetail.newInstance(
                    oi.getProductId().toString(),
                    oi.getProductName(),
                    BigDecimalUtil.mul(oi.getCurrentUnitPrice().doubleValue(), new Double(100).doubleValue()).longValue(),
                    oi.getQuantity());
            // 创建好一个商品后添加至商品明细列表
            goodsDetailList.add(goods1);
        }

        // 创建扫码支付请求builder，设置请求参数
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(subject)
                .setTotalAmount(totalAmount)
                .setOutTradeNo(outTradeNo)
                .setUndiscountableAmount(undiscountableAmount)
                .setSellerId(sellerId)
                .setBody(body)
                .setOperatorId(operatorId)
                .setStoreId(storeId)
                .setExtendParams(extendParams)
                .setTimeoutExpress(timeoutExpress)
                //支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                .setNotifyUrl(PropertiesUtil.getProperty("alipay.callback.url"))
                .setGoodsDetailList(goodsDetailList);

        /** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
         *  Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
         */
        Configs.init("zfbinfo.properties");

        /** 使用Configs提供的默认参数
         *  AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
         */
        AlipayTradeService tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();

        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);

        switch (result.getTradeStatus()) {
            case SUCCESS:
                log.info("支付宝预下单成功: )");
                AlipayTradePrecreateResponse response = result.getResponse();
                dumpResponse(response);
                //生成二维码，上传到服务器，最后组装url，返回给前端
                File folder = new File(path);
                if (folder.exists()) {
                    //不存在，创建目录
                    folder.setWritable(true);
                    folder.mkdirs();
                }
                // 需要修改为运行机器上的路径
                // 细节细节细节 加 /
                String qrPath = String.format(path + "/qr-%s.png", response.getOutTradeNo());
                //生产一个文件，订单号作为文件名命名
                String qrFileName = String.format("qr-%s.png", response.getOutTradeNo());
                ZxingUtils.getQRCodeImge(response.getQrCode(), 256, qrPath);

                File targetFile = new File(path, qrFileName);
                try {
                    FTPUtil.uploadFile(Lists.newArrayList(targetFile));
                } catch (IOException e) {
                    log.error("上传二维码异常", e);
                }
                log.info("filePath:" + qrPath);
                //拼接url
                String qrUrl = PropertiesUtil.getProperty("ftp.server.http.prefix") + targetFile.getName();
                resultMap.put("qrUrl", qrUrl);
                return ServerResponse.createBySuccess(resultMap);
            case FAILED:
                log.error("支付宝预下单失败!!!");
                return ServerResponse.createByErrorMessage("支付宝预下单失败!!!");
            case UNKNOWN:
                log.error("系统异常，预下单状态未知!!!");
                return ServerResponse.createByErrorMessage("系统异常，预下单状态未知!!!");
            default:
                log.error("不支持的交易状态，交易返回异常!!!");
                return ServerResponse.createByErrorMessage("不支持的交易状态，交易返回异常!!!");
        }
    }

    // 简单打印应答
    private void dumpResponse(AlipayResponse response) {
        if (response != null) {
            log.info(String.format("code:%s, msg:%s", response.getCode(), response.getMsg()));
            if (StringUtils.isNotEmpty(response.getSubCode())) {
                log.info(String.format("subCode:%s, subMsg:%s", response.getSubCode(),
                        response.getSubMsg()));
            }
            log.info("body:" + response.getBody());
        }
    }

    @Override
    public ServerResponse aliCallback(Map<String, String> params) {
        //拿出订单号
        Long orderNo = Long.parseLong(params.get("out_trade_no"));
        //拿出支付宝的交易号
        String tradeNo = params.get("trade_no");
        //交易状态
        String tradeStatus = params.get("trade_status");

        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            return ServerResponse.createByErrorMessage("非mmall商城订单，回调忽略");
        }
        if (order.getStatus() >= OrderStatusEnum.PAID.getCode()) {
            return ServerResponse.createBySuccess("支付宝重复调用");
        }
        if (Const.AlipayCallBack.TRADE_STATUS_TRADE_SUCCESS.equals(tradeStatus)) {
            //付款时间
            order.setPaymentTime(DateTimeUtil.strToDate(params.get("gmt_payment")));
            //交易成功
            order.setStatus(OrderStatusEnum.PAID.getCode());
            //修改订单状态
            orderMapper.updateByPrimaryKeySelective(order);
        }
        //支付信息
        PayInfo payInfo = new PayInfo();
        payInfo.setUserId(order.getUserId());
        payInfo.setOrderNo(order.getOrderNo());
        payInfo.setPayPlatform(PayPlatformEnum.ALIPAY.getCode());
        payInfo.setPlatformNumber(tradeNo);
        payInfo.setPlatformStatus(tradeStatus);

        //添加一条支付详情
        payInfoMapper.insert(payInfo);
        return ServerResponse.createBySuccess();
    }

    @Override
    public ServerResponse queryOrderPayStatus(Integer userId, Long orderNo) {
        Order order = orderMapper.selectByUserIdAndOrderNo(userId, orderNo);
        if (order == null) {
            return ServerResponse.createByErrorMessage("非mmall商城订单，回调忽略");
        }
        //付款，code返回0
        if (order.getStatus() >= OrderStatusEnum.PAID.getCode()) {
            return ServerResponse.createBySuccess(OrderStatusEnum.codeOf(order.getStatus()));
        }
        //未付款，code返回1
        return ServerResponse.createByErrorMessage(OrderStatusEnum.codeOf(order.getStatus()).toString());
    }


    @Override
    public ServerResponse create(Integer userId, Integer shippingId) {
        //从购物车中获取被勾选的商品
        List<Cart> cartList = cartMapper.selectCheckedCartBuUserId(userId);
        //获取订单明细
        ServerResponse<List<OrderItem>> serverResponse = this.getCratOrderItem(userId, cartList);
        if (!serverResponse.isSuccess()) {
            return serverResponse;
        }
        //计算订单的总价
        List<OrderItem> orderItemList = serverResponse.getData();
        //计算总价
        BigDecimal payment = getOrderTotalPrice(orderItemList);

        //生成订单
        Order order = this.assembleOrder(userId, shippingId, payment);
        if (order == null) {
            return ServerResponse.createByErrorMessage("生成订单号错误");
        }
        if (CollectionUtils.isEmpty(orderItemList)) {
            return ServerResponse.createByErrorMessage("购物车为空");
        }
        for (OrderItem oi : orderItemList) {
            oi.setOrderNo(order.getOrderNo());
        }
        //把这条订单的item，批量插入order_item表
        orderItemMapper.batchInsert(orderItemList);

        //生成成功，我们要减少产品的库存
        this.reduceProductStock(orderItemList);
        //清空购物车
        this.cleanCart(cartList);
        //返回给前端数据
        OrderVo orderVo = assembleOrderVo(order, orderItemList);
        return ServerResponse.createBySuccess(orderVo);
    }

    @Override
    public ServerResponse cancel(Integer userId, Long orderNo) {
        Order order = orderMapper.selectByUserIdAndOrderNo(userId, orderNo);
        if (order == null) {
            return ServerResponse.createByErrorMessage("该用户此订单不存在");
        }
        if (order.getStatus() != OrderStatusEnum.NO_PAY.getCode()) {
            return ServerResponse.createByErrorMessage("已付款，无法取消退款");
        }
        Order updateOrder = new Order();
        updateOrder.setStatus(OrderStatusEnum.CANCELED.getCode());
        updateOrder.setId(order.getId());
        int rowCount = orderMapper.updateByPrimaryKeySelective(updateOrder);
        if (rowCount > 0) {
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByErrorMessage("订单取消失败");
    }

    @Override
    public ServerResponse getOrderCartProduct(Integer userId) {
        OrderProductVo orderProductVo = new OrderProductVo();
        //从购物车中获取数据
        List<Cart> cartList = cartMapper.selectCheckedCartBuUserId(userId);
        ServerResponse<List<OrderItem>> cratOrderItem = this.getCratOrderItem(userId, cartList);
        if (!cratOrderItem.isSuccess()) {
            return cratOrderItem;
        }
        List<OrderItem> orderItemList = cratOrderItem.getData();
        List<OrderItemVo> resultListVo = Lists.newArrayList();
        BigDecimal payment = new BigDecimal("0");
        for (OrderItem oi : orderItemList) {
            payment = BigDecimalUtil.add(payment.doubleValue(), oi.getTotalPrice().doubleValue());
            resultListVo.add(assembleOrderItem(oi));
        }
        orderProductVo.setProductTotalPrice(payment);
        orderProductVo.setOrderItemVoList(resultListVo);
        orderProductVo.setImagehost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        return ServerResponse.createBySuccess(orderProductVo);
    }

    @Override
    public ServerResponse getOrderDetail(Integer userId, Long orderNo) {
        Order order = orderMapper.selectByUserIdAndOrderNo(userId, orderNo);
        if (order != null) {
            List<OrderItem> orderItemList = orderItemMapper.getByOrderNoByUserId(orderNo, userId);
            OrderVo orderVo = this.assembleOrderVo(order, orderItemList);
            return ServerResponse.createBySuccess(orderVo);
        }
        return ServerResponse.createByErrorMessage("没有找到该订单");
    }

    @Override
    public ServerResponse getOrderList(Integer userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.selectByUserId(userId);
        List<OrderVo> orderVoList = assembleOrderVoList(orderList, userId);
        PageInfo resultPage = new PageInfo(orderList);
        resultPage.setList(orderVoList);
        return ServerResponse.createBySuccess(resultPage);
    }

    @Override
    public ServerResponse<PageInfo> getManageList(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        //查询所有订单
        List<Order> orderList = orderMapper.selectAllOrOrder();
        List<OrderVo> orderVoList = assembleOrderVoList(orderList, null);
        PageInfo resultPage = new PageInfo(orderList);
        resultPage.setList(orderVoList);
        return ServerResponse.createBySuccess(resultPage);
    }

    @Override
    public ServerResponse<OrderVo> getManageDetail(Long orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order != null) {
            List<OrderItem> orderItemList = orderItemMapper.getByOrderNo(orderNo);
            OrderVo orderVo = assembleOrderVo(order, orderItemList);


            return ServerResponse.createBySuccess(orderVo);
        }
        return ServerResponse.createByErrorMessage("订单不存在");
    }

    @Override
    public ServerResponse<PageInfo> getOrderSearch(Long orderNo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order != null) {
            List<OrderItem> orderItemList = orderItemMapper.getByOrderNo(orderNo);
            OrderVo orderVo = assembleOrderVo(order, orderItemList);
            PageInfo resultPage = new PageInfo(Lists.newArrayList(order));
            resultPage.setList(Lists.newArrayList(orderVo));
            return ServerResponse.createBySuccess(resultPage);
        }
        return ServerResponse.createByErrorMessage("订单不存在");
    }

    @Override
    public ServerResponse<String> orderSendGoods(Long orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order != null) {
            //判断订单是否支付成功
            if (order.getStatus() == OrderStatusEnum.PAID.getCode()) {
                //更新成已发货
                order.setStatus(OrderStatusEnum.SHIPPED.getCode());
                order.setSendTime(new Date());
                int count = orderMapper.updateByPrimaryKeySelective(order);
                return ServerResponse.createBySuccess("发货成功");
            }

        }
        return ServerResponse.createByErrorMessage("订单不存在");
    }

    @Override
    public void closeOrder(Integer hour) {
        Date closeDateTime = DateUtil.offsetHour(new Date(), -hour);
        List<Order> orderList = orderMapper.closeOrder(OrderStatusEnum.NO_PAY.getCode(), closeDateTime);
        for (Order order : orderList) {
            List<OrderItem> orderItems = orderItemMapper.getByOrderNo(order.getOrderNo());
            for (OrderItem item : orderItems) {
                //一定要用主键where条件，防止锁表。同时必须是支持MySQL的InnoDB
                Integer stock = productMapper.selectStockByProductId(item.getProductId());
                //考虑到已生成的订单的商品，被删除的情况
                if (stock == null) {
                    continue;
                }
                Product product = new Product();
                product.setId(item.getProductId());
                //数据库中的库存 + 关闭订单中商品的数量
                product.setStock(stock + item.getQuantity());
                productMapper.updateByPrimaryKeySelective(product);
            }
            orderMapper.closeOrderByOrderId(order.getId());
            log.info("关闭订单，orderId{}", order.getId());
        }
    }

    //orderList --> List<OrderVo>
    private List<OrderVo> assembleOrderVoList(List<Order> orderList, Integer userId) {
        List<OrderVo> resultOrderVoList = Lists.newArrayList();
        for (Order order : orderList) {
            List<OrderItem> orderItemList = Lists.newArrayList();
            //判断管理员
            if (userId == null) {
                //管理员查询的时候，不需要userId
                orderItemList = orderItemMapper.getByOrderNo(order.getOrderNo());
            } else {
                //获取订单明细
                orderItemList = orderItemMapper.getByOrderNoByUserId(order.getOrderNo(), userId);
            }
            OrderVo orderVo = assembleOrderVo(order, orderItemList);
            resultOrderVoList.add(orderVo);
        }
        return resultOrderVoList;
    }


    //组装orderVo
    private OrderVo assembleOrderVo(Order order, List<OrderItem> orderItemList) {
        OrderVo orderVo = new OrderVo();
        orderVo.setOrderNo(order.getOrderNo());
        orderVo.setPayment(order.getPayment());
        orderVo.setPaymentType(order.getPaymentType());
        orderVo.setPaymentTypeDesc(PaymentTypeEnum.codeOf(order.getPaymentType()).getValue());

        orderVo.setPostage(order.getPostage());
        orderVo.setStatus(order.getStatus());
        orderVo.setStatusDesc(OrderStatusEnum.codeOf(order.getStatus()).getValue());

        orderVo.setShippingId(order.getShippingId());
        //shipping
        Shipping shipping = shippingMapper.selectByPrimaryKey(order.getShippingId());
        if (shipping != null) {
            orderVo.setReceiverName(shipping.getReceiverName());
            orderVo.setShippingVo(this.assembleShippingVo(shipping));
        }
        orderVo.setPaymentTime(DateTimeUtil.dateToStr(order.getPaymentTime()));
        orderVo.setSendTime(DateTimeUtil.dateToStr(order.getSendTime()));
        orderVo.setEndTiem(DateTimeUtil.dateToStr(order.getEndTime()));
        orderVo.setCloseTime(DateTimeUtil.dateToStr(order.getCloseTime()));
        orderVo.setCreateTime(DateTimeUtil.dateToStr(order.getCreateTime()));


        List<OrderItemVo> orderItemVoList = Lists.newArrayList();
        //图片地址
        orderVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));
        for (OrderItem oi : orderItemList) {
            OrderItemVo orderItemVo = this.assembleOrderItem(oi);
            orderItemVoList.add(orderItemVo);
        }
        orderVo.setOrderItemVoList(orderItemVoList);
        return orderVo;
    }

    /**
     * 将pojo转换成vo
     *
     * @param orderItem
     * @return
     */
    private OrderItemVo assembleOrderItem(OrderItem orderItem) {
        OrderItemVo orderItemVo = new OrderItemVo();
        //这个商品的订单号
        orderItemVo.setOrderNo(orderItem.getOrderNo());
        orderItemVo.setProductId(orderItem.getProductId());
        orderItemVo.setProductName(orderItem.getProductName());
        orderItemVo.setProductImage(orderItem.getProductImage());
        orderItemVo.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
        orderItemVo.setQuantity(orderItem.getQuantity());
        orderItemVo.setTotalPrice(orderItem.getTotalPrice());
        orderItemVo.setCreateTime(DateTimeUtil.dateToStr(orderItem.getCreateTime()));
        return orderItemVo;
    }

    private ShippingVo assembleShippingVo(Shipping shipping) {
        ShippingVo shippingVo = new ShippingVo();
        shippingVo.setReceiverName(shipping.getReceiverName());
        shippingVo.setReceiverAddress(shipping.getReceiverAddress());
        shippingVo.setReceiverCity(shipping.getReceiverCity());
        shippingVo.setReceiverDistrict(shipping.getReceiverDistrict());
        shippingVo.setReceiverMobile(shipping.getReceiverMobile());
        shippingVo.setReceiverPhone(shipping.getReceiverPhone());
        shippingVo.setReceiverZip(shipping.getReceiverZip());
        shippingVo.setReceiverProvince(shipping.getReceiverProvince());
        return shippingVo;
    }

    //清空购物车的方法
    private void cleanCart(List<Cart> cartList) {
        for (Cart c : cartList) {
            cartMapper.deleteByPrimaryKey(c.getId());
        }
    }

    //减少库存的方法
    private void reduceProductStock(List<OrderItem> orderItemList) {
        for (OrderItem oi : orderItemList) {
            //根据商品id，查找库存
            Product product = productMapper.selectByPrimaryKey(oi.getProductId());
            //仓库中的库存 - 订单中商品的个数
            product.setStock(product.getStock() - oi.getQuantity());
            productMapper.updateByPrimaryKeySelective(product);
        }
    }

    //生成订单的方法
    private Order assembleOrder(Integer userId, Integer shippingId, BigDecimal payment) {
        Order order = new Order();
        long orderNo = this.generateOrderNo();
        order.setOrderNo(orderNo);
        //状态是 未付款
        order.setStatus(OrderStatusEnum.NO_PAY.getCode());
        //运费
        order.setPostage(0);
        //支付类型
        order.setPaymentType(PaymentTypeEnum.ONLINE_PAY.getCode());   //在线支付
        order.setPayment(payment);
        order.setUserId(userId);
        order.setShippingId(shippingId);
        //发货时间
        //付款时间
        int rowCount = orderMapper.insert(order);
        if (rowCount > 0) {
            return order;
        }
        return null;
    }

    //生成订单号
    private long generateOrderNo() {
        /**
         * 生成订单号
         * 非常重要！！
         */
        //目前就用时间戳 + 100 以内的随机数，后期拓展
        long currentTime = System.currentTimeMillis();
        //生成100以内随机数
        long randomOrderNo = currentTime + new Random().nextInt(100);
        //返回时间戳加随机数
        return randomOrderNo;
    }


    //计算总价的方法
    private BigDecimal getOrderTotalPrice(List<OrderItem> orderItemList) {
        BigDecimal payment = new BigDecimal("0");
        for (OrderItem orderItem : orderItemList) {
            payment = BigDecimalUtil.add(payment.doubleValue(), orderItem.getTotalPrice().doubleValue());
        }
        return payment;
    }

    //将购物车中勾选的产品，组装成订单中商品的列表
    private ServerResponse<List<OrderItem>> getCratOrderItem(Integer userId, List<Cart> cartList) {
        ArrayList<OrderItem> orderItemList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(cartList)) {
            return ServerResponse.createByErrorMessage("购物车为空");
        }
        //校验购物车的数据，包括产品的状态和数量
        for (Cart cartItem : cartList) {
            OrderItem orderItem = new OrderItem();
            Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
            //判断产品在线
            if (ProductStatusEnum.ON_SALE.getCode() != product.getStatus()) {
                return ServerResponse.createByErrorMessage("产品" + product.getName() + "不是在线售卖状态");
            }
            //库存校验
            if (cartItem.getQuantity() > product.getStock()) {
                return ServerResponse.createByErrorMessage("产品" + product.getName() + "库存不足");
            }
            //开始组装
            orderItem.setUserId(userId);
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentUnitPrice(product.getPrice());
            orderItem.setQuantity(cartItem.getQuantity());
            //计算总计
            orderItem.setTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartItem.getQuantity()));

            //添加到集合中
            orderItemList.add(orderItem);
        }
        return ServerResponse.createBySuccess(orderItemList);
    }

}
